package group.rober.saber.holder;

import group.rober.saber.web.RequestParameterMap;
import org.apache.shiro.web.session.HttpServletSession;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * HTTP快速工具获取
 * Created by tisir<yangsong158@qq.com> on 2017-05-31
 */
public abstract class WebHolder {

    private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<HttpServletRequest>();
    private static final ThreadLocal<HttpServletResponse> responseHolder = new ThreadLocal<HttpServletResponse>();
    private static final ThreadLocal<HttpSession> sessionHolder = new ThreadLocal<HttpSession>();
    private static ServletContext SERVLET_CONTEXT = null;

    public static void setRequest(HttpServletRequest request){
        requestHolder.set(request);
    }
    public static HttpServletRequest getRequest() {
        return requestHolder.get();
//        ServletRequestAttributes sra = getServletRequestAttributes();
//        if(sra == null){
//            throw new NullPointerException("there is no web context environment support");
//        }
//        return sra.getRequest();
    }

    public static void setResponse(HttpServletResponse response){
        responseHolder.set(response);
    }
    public static HttpServletResponse getResponse() {
        return responseHolder.get();
    }
    public static void setServletContext(ServletContext servletContext){
        SERVLET_CONTEXT = servletContext;
    }
    public static ServletContext getServletContext(){
        return SERVLET_CONTEXT;
//        WebApplicationContext wac = getWebApplicationContext();
//        if(wac == null){
//            throw new NullPointerException("there is no web context environment support");
//        }
//        return wac.getServletContext();
    }
    public static void setSession(HttpSession session){
        sessionHolder.set(session);
    }
    public static HttpSession getSession(){
        return sessionHolder.get();
    }

    public void clear(){
        requestHolder.remove();
        responseHolder.remove();
        sessionHolder.remove();
    }


//    public static ServletRequestAttributes getServletRequestAttributes() {
//        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
//    }

//    public static WebApplicationContext getWebApplicationContext(){
//        return ContextLoader.getCurrentWebApplicationContext();
//    }


    public static RequestParameterMap getRequestParameterMap(){
        return new RequestParameterMap(getRequest());
    }



}
